package router

import (
	"io/ioutil"
	"log"
	"net/http"
	"strconv"
	"time"

	"github.com/streadway/amqp"
	cedar_session "github.com/tungyao/cedar-session"
)

// 建立用户之后或获取到 用户的个人消息
// 临时用户不需要注册
// 存储用户会按照 uuid|name 进行存储 记得在创建用户名时不允许 | 的出现
var (
	MQ  *amqp.Channel
	err error
)

func init() {
	// 和mq建立连接
	conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/")
	if err != nil {
		log.Fatalln(err)
	}
	MQ, err = conn.Channel()
	if err != nil {
		log.Fatalln(err)
	}
	MQ.Confirm(false)
	log.Println("connect RabbitMQ success")

}
func CreateUser(w http.ResponseWriter, r *http.Request, s cedar_session.Session) {
	// 获取到前端穿过来的json
	// name 必须
	// uuid
	// time
	data, err := ioutil.ReadAll(r.Body)
	if err != nil {
		log.Panicln(err)
	}
	user := &ImCreateUser{}
	user.UnmarshalJSON(data)
	q, err := MQ.QueueDeclare("im_create_user", true, false, false, false, nil)
	if err != nil {
		log.Panicln(err)
	}
	user.UUID = createUUID(strconv.Itoa(int(time.Now().UnixNano())) + r.RemoteAddr)
	user.Time = time.Now().Unix()
	data, _ = user.MarshalJSON()
	// 推送至队列 让后端来处理插入用户
	err = MQ.Publish("", q.Name, false, false, amqp.Publishing{
		ContentType:  "application/json",
		DeliveryMode: amqp.Persistent,
		Body:         data,
	})
	ack, nack := MQ.NotifyConfirm(make(chan uint64), make(chan uint64))
	if err != nil {
		log.Panicln(err)
	}
	// 返回前端
	// uuid
	w.Header().Set("Content-Type", "application/json")
	select {
	case <-ack:
		w.Write(data)
	case <-nack:
		ToErrorJson(w, "创建失败")
	}
}

// 判断用户是否在线
func GetUserOnline(w http.ResponseWriter, r *http.Request, s cedar_session.Session) {
	// 检查app
	uuid := r.URL.Query().Get("uuid")
	appid := r.URL.Query().Get("appid")
	secret := r.URL.Query().Get("secret")
	if appid == "" || secret == "" {
		ToErrorJson(w, "appid or secret is nil")
		return
	}
	if obj := EtcdGetSingle("/app/" + appid); obj == nil {
		ToErrorJson(w, "app is not found , please check it")
		return
	} else {
		if secret != string(obj) {
			ToErrorJson(w, "check secret failed")
			return
		}
	}
	if user := allClients.Get([]byte(uuid)); user != nil {
		ToSuccJson(w, "online")
	} else {
		ToSuccJson(w, "offline")
	}
}
